$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})

var bang_itemspan = document.getElementsByClassName('bang_item')[0].getElementsByTagName('span');
var bangtop = document.getElementsByClassName('bang_con_1');
for (var i=0;i<bang_itemspan.length; i++){
     bang_itemspan[i].index = i;
     bang_itemspan[i].onclick = function () {
          for (var j=0;j<bang_itemspan.length;j++){
                bang_itemspan[j].className = '';
                bangtop[j].style.display = 'none';
          }
          this.className = 'active';
          bangtop[this.index].style.display = 'block';
     }
}

/**
 * 关注
 */
function attent(op) {
    if (!isLogin) {
          layer.msg('请先登录',{icon:2});
          return;
    }
    if (op==1){
        url = '/live/addatten';
        str = '关注';
    }else{
        url = '/live/delatten'
        str = '取消关注'
    }
    var data = {room:room};
    $.ajax({
        type:"POST",
        url:url,
        data:data,
        dataType:"json",
        success:function (res) {
            if (res['code'] == 200) {
                layer.msg(str+'成功',{icon:1});
            }else{
                layer.msg(res['msg'],{icon:2});
            }
        }
    })
}

/**
 * 调试摄像头
 */
function testVideo() {
    var cameraList = myPublisher.getCameraList(); // 获取摄像头列表
    if (cameraList[0].value == '') {
         return;
    }
    myPublisher.startPreview(0);
}

/**
 * 开播
 */
function startRoom(_this) {
    var livestatus = document.getElementsByClassName('live_status')[0];
    var num = _this.getAttribute('data-num');
    var show_paly = document.getElementsByClassName('show_paly')[0];
    var sta =  _this.getAttribute('status');
    if (sta==0) {
        data = {num:num};
        $.ajax({
            type:"POST",
            url:"/live/start-live",
            data:data,
            dataType:"json",
            success:function (data) {
                if (data['code']==200) {
                    _this.setAttribute('status',1);
                    var time = document.getElementsByClassName('t')[0];
                    var no_start = document.getElementsByClassName('no_start')[0];
                    var webpush = document.getElementsByClassName('webpush')[0];
                    webpush.setAttribute('pushurl',data['playurl']);
                    time.setAttribute('time',0);
                    initpush(data['playurl']);
                    // myPublisher.setCamera(0) //功能：设置推流摄像头 参数：
                    // myPublisher.setMicroPhone(0); // 功能：设置推流麦克风
                    // myPublisher.startPublish( // 开始推流
                    //     "rtmp://16234.livepush.myqcloud.com/live/16234_53d873e154?bizid=16234&txSecret=c31a85a2187f21a93510a8c4999e2b0e&txTime=5A159EFF",
                    //     {
                    //         videoWidth: 700,
                    //         videoHeight: 400,
                    //         fps: 15,
                    //         bitrate: 600,
                    //     }, function(code, desc) {
                    //         // 推流错误时触发
                    //     });
                    // 开始计时
                    show_paly.removeChild(no_start);
                    startTimeDown();
                    // 改变状态
                    livestatus.className = 'live_status liveed';
                    livestatus.innerHTML = '直播中'
                }
            }
        })
    }else{
        data = {num:num};
        $.ajax({
            type:"POST",
            url:"/live/end-live",
            data:data,
            dataType:"json",
            success:function (data) {
                if (data['code']==200) {
                    _this.setAttribute('status',0);
                    clearInterval(timedown);
                    var no_start = document.createElement('div');
                    no_start.className = 'no_start';
                    no_start.innerHTML = '未开启直播';
                    show_paly.appendChild(no_start);
                    // 改变状态
                    livestatus.className = 'live_status liveing';
                    livestatus.innerHTML = '已休播';
                    localStorage.setItem('isWebPush',0);
                }
            }
        })
    }

    function initpush(pushurl) {
        var pushinput = document.getElementsByClassName('w_form')[0].getElementsByTagName('input');
        pushUrl = pushurl.split('?');
        pushinput[0].value = pushUrl[0];
        pushinput[1].value = pushUrl[1];
    }

    // 开始计时
    function startTimeDown() {
        timedown = setInterval(function () {
            var time = document.getElementsByClassName('t')[0];
            var t = parseInt(time.getAttribute('time'));
            t+=1;
            time.setAttribute('time',t);
            // 格式化时间 00:00;
            times = data_format(t);
            time.innerHTML = times;
        },1000)
    }

    //补零函数
    function fill_zero(num){
        if(num<=9){
            return "0"+num;
        }else{
            return ""+num;
        }
    }

    //时间格式化函数
    function data_format(time){
        var h,s,m,remain;
        h= fill_zero(parseInt(time/3600));
        remain = time%3600;
        m = fill_zero(parseInt(remain/60));
        remain = fill_zero(parseInt(remain%60));
        s = remain;
        return m+":"+s;
    }

}

$room_template = {
    'base_tmpl':'<div class="dialg animated bounceIn" id="dowebok"><div class="dialg_title">{title}</div><div class="dialg_cont">{content}</div><div class="dialg_btn"><a href="JavaScript:;" {evt}>确定</a><a href="javascript:;" onclick="closeAdmin(0)">取消</a></div></div></div>',
    'admin_temp':'<div class="confirmtips">你确定要禁止其用户在本房间发言?<p>禁言后该用户将无法在本房间发表任何言论</p><input type="hidden" value="{id}" id="hid_inp"></div>',
    'admin_temp1':'<div class="confirmtips">你确定要设置其用户为本间房管?<p>设置房管后,该用户将有权利禁言本房间的用户</p><input type="hidden" value="{id}" id="hid_inp"></div>'
}

function stopBubble(e) {
//如果提供了事件对象，则这是一个非IE浏览器
    if ( e && e.stopPropagation )
    //因此它支持W3C的stopPropagation()方法
        e.stopPropagation();
    else
    //否则，我们需要使用IE的方式来取消事件冒泡
        window.event.cancelBubble = true;
}
$('#danmbox').on('click',function () {
    closedmMenu();
})

function closedmMenu(){
    var dmMenu =  document.getElementsByClassName('u_op');
    for (var i=0;i<dmMenu.length;i++) {
        dmMenu[i].style.top = '35px';
        index = i;
        setTimeout(function () {
            dmMenu[index].style.display = 'none';
        }, 80)
    }
}

function showLw() {
    var lw_box = document.getElementsByClassName('lw_collect_box')[0];
    lw_box.style.display = 'block';
}

function closeLw() {
    var lw_box = document.getElementsByClassName('lw_collect_box')[0];
    lw_box.style.display = 'none';
}
var tiimer = null;
tiimer = setInterval(timedown,1000);
function timedown() {
     var time = document.getElementsByClassName('lw_time')[0];
     if (time==undefined) {
          return;
     }
     var t = time.getAttribute('time');
     var dt = parseInt(t)-1;
     time.innerHTML = data_format(dt);
     updatetime();
     time.setAttribute('time',dt);
};

//时间格式化函数
function data_format(time){
    var h,s,m,remain;
    h= fill_zero(parseInt(time/3600));
    remain = time%3600;
    m = fill_zero(parseInt(remain/60));
    remain = fill_zero(parseInt(remain%60));
    s = remain;
    return m+":"+s;
}

//补零函数
function fill_zero(num){
    if(num<=9){

        return "0"+num;

    }else{
        return ""+num;
    }
}

/**
 * 更新时间至后台
 */
function updatetime() {
    var time = Math.random();
    $.ajax({
        type:"POST",
        url:"/live/receivegift-time-update",
        data:{time:time},
        dataType:"json",
        success:function (res) {
             if (res['code']==201) {
                     var lw_item_box    = document.getElementsByClassName('lw_collect_con');
                     var lw_item_p      = lw_item_box[res['data']-1].getElementsByTagName('p')[0];
                     lw_item_p.innerHTML = '待领取';
                     clearInterval(tiimer);
             }
        }
    })
}

/**
 * 添加房管
 */
function addRoomAdmin() {
    var uid = document.getElementById('hid_inp').value;
    var data = {uid:uid,room:room};
    $.ajax({
        type:"POST",
        url:"/live/addroomadmin",
        data:data,
        dataType:"json",
        success:function (res) {
            if (res['code'] == 200){
                 layer.msg('添加成功',{icon:1});
            }else{
                 layer.msg(res['msg'],{icon:1});
            }
            closeAdmin();
        }
    })
}

/**
 * 禁言用户
 */
function addRoomgag() {
    var uid = document.getElementById('hid_inp').value;
    var data = {uid:uid,room:room};
    $.ajax({
        type:"POST",
        url:"/live/addroombag",
        data:data,
        dataType:"json",
        success:function (res) {
            if (res['code'] == 200){
                layer.msg('添加成功',{icon:1});
            }else{
                layer.msg(res['msg'],{icon:1});
            }
            closeAdmin();
        }
    })
}

/**
 * 显示右侧弹幕菜单
 * @param _this
 */
function showdmMenu(_this) {
    var dmMenu =  _this.getElementsByClassName('u_op')[0];
    if (dmMenu==undefined){
         return;
    }
    dmMenu.style.display = 'block';
    setTimeout(function () {
        dmMenu.style.top = '25px';
    },20);
    stopBubble(_this);

}

function webpush() {
    if (isLive==0) {
        layer.msg('请先打开直播开关',{icon:2});
        return;
    }
    localStorage.setItem('isWebPush',1);
}

function roomAdmin(_this,flag) {
    var dialg = document.getElementsByClassName('dialg')[0];
    if (dialg) {
        closeAdmin();
    }
    var uid = _this.getAttribute('uid');
    if (flag==0){
        $html = $room_template.base_tmpl.replace(/\{title\}/,'房管特权').replace(/\{content\}/,$room_template.admin_temp).replace(/\{id\}/,uid).replace(/\{evt\}/,'onclick=addRoomgag(this)');
        document.body.innerHTML += $html
    }else{
        $html = $room_template.base_tmpl.replace(/\{title\}/,'主播特权').replace(/\{content\}/,$room_template.admin_temp1).replace(/\{id\}/,uid).replace(/\{evt\}/,'onclick=addRoomAdmin(this)');
        document.body.innerHTML += $html
    }
    closedmMenu();
}

function closeAdmin() {
    var dialg = document.getElementsByClassName('dialg')[0];
    document.body.removeChild(dialg);
}
function showTips(html) {
    var message = document.getElementsByClassName('message')[0];
    var messagetext = message.getElementsByTagName('p')[0];
    messagetext.innerHTML = html;
    $(".message").transition({top: -31}, 200, 'linear', function(){
        setTimeout(function () {
            $(".message").css({top:0});
        },3000)
    });
}

function showpush() {
     if (isLive==0) {
          layer.msg('请先打开直播开关',{icon:2});
          return;
     }
     var push = document.getElementById('push');
     push.style.display = 'block';
}

function closepush() {
    var push = document.getElementById('push');
    push.style.display = 'none';
}

function getgift(_this) {
    $.ajax({
        type:"POST",
        url:"/live/receivegift",
        data:{time:Math.random()},
        dataType:"json",
        success:function (res) {
            console.log(res);
            if (res['code']==200){
                _this.innerHTML = '已领取';
                 // 领取成功执行逻辑
                var lw_item_icon   = document.getElementsByClassName('lw_item_icon')
                var lw_item_box    = document.getElementsByClassName('lw_item');
                var lw_item_p      = lw_item_box[res['data']['giftnow']].getElementsByTagName('p')[0];
                lw_item_icon[res['data']['giftnow']].className = 'lw_item_icon active';
                lw_item_p.innerHTML = '计时中<b class="lw_time" time="'+res['data']['w_time']+'">0:00</b>';
                tiimer = setInterval(timedown,1000);
            }else{
                 layer.msg(res['msg'],{icon:2})
            }
        }
    })
}